<?php

declare(strict_types=1);

namespace App\Service;

use Hyperf\Utils\ApplicationContext;
use Hyperf\Redis\Redis;
use App\Model\User;

class WebsocketRedisCurd
{
    private $key = 'message';

    public function redis()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        return  $redis;
    }

    //设置FID
    public function setFid($uid, $fd)
    {
        $redis = $this->redis();
        $redis->set($this->key . '_' . $uid, $fd);
    }

    //获取FID
    public function getFid($id)
    {
        $redis = $this->redis();
        return $redis->get($this->key . '_' . $id);
    }

    //获取用户信息
    public function getUserInfo($uid)
    {
        $redis = $this->redis();
        $data = $redis->hGetAll($this->key . '_userinfo_' . $uid);
        if (empty($data)) {
            $data = User::query()->where('id', $uid)->first()->toArray();
            $redis = $this->redis();
            $redis->hMset($this->key . '_userinfo_' . $uid, $data);
        }
        return $data;
    }


    //设置用户列表
    public function setUserList($uid, $toid)
    {
        $redis = $this->redis();
        $redis->zAdd($this->key . '_userlist_' . $uid, time(), $toid);
    }

    //获取用户列表
    public function getUserList($uid)
    {
        $redis = $this->redis();
        return $redis->zRevrange($this->key . '_userlist_' . $uid, 0, -1);
    }

    //设置用户最后一条消息
    public function setLastMessage($uid,$toid,$data)
    {
        $redis = $this->redis();
        $redis->hMset($this->key . '_last_' . $uid.'_to_'.$toid, ['data' => serialize($data), 'status' => 0]);
    }

    //获取用户最后一条消息
    public function getLastMessage($fid,$uid)
    {
        $redis = $this->redis();
        return $redis->hGetAll($this->key . '_last_'. $fid.'_to_' .$uid);
    }

    //设置用户最新数据
    public function setNewUserMessage($uid,$toid,$mid, $content)
    {
        $redis = $this->redis();
        $data['content'] = $content;
        $data['mid'] = $mid;
        $data['datetime'] = date('Y-m-d H:i:s');
        $redis->lPush($this->key . '_new_message_' . $uid.'_to_'.$toid, serialize($data));
        $redis->ltrim($this->key . '_new_message_' . $uid.'_to_'.$toid, 0, 50);
    }

    //获取用户最新数据
    public function getUserMessage($fid,$uid,$start=0,$end=10)
    {
        $redis = $this->redis();
        $data =  $redis->lrange($this->key . '_new_message_' . $fid.'_to_'.$uid,$start,$end);
        $result = [];
        if ($data !== false && !empty($data)) {
            $result = $data;
        }
        return $result;
    }
}
